package com.ys.openapi.organization.department;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.erp.utils.HttpUtils;
import com.erp.utils.PropertiesUtils;
import com.erp.utils.WebApiUtils;
import com.ys.openapi.organization.entity.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class User {

    //新增用户
    public Object addUser(UserEntity user,String access_token)throws Exception{
        //先判断部门是否存在
        Department dept=new Department();
        Map<String, Object> map = dept.searchDepartmentByDepartmentName(user.getDepartmentId(), true);
        if(map.get(user.getDepartmentId())==null){
            return null;
        }
        user.setDepartmentId(map.get(user.getDepartmentId()).toString());
        //查询用户是否存在
        UserSearchEntity use=new UserSearchEntity();
        //use.setFilterType("admin");
        use.setPage(0);
        use.setSize(1000);
        use.setWd(user.getName());
        Map<String, Object> searchuser = searchuser(use, access_token);
        if(searchuser.get("name") !=null){
            return 0;
        }
        List li=new ArrayList();
        //取角色id
        List roleIds = user.getRoleIds();
        Role role=new Role();
        RoleVo vo=new RoleVo();
        for(int i=0;i<roleIds.size();i++){
            vo.setRoleName(roleIds.get(i).toString());
            vo.setRoleType("OTHER");
            Map<String, Object> role_by_name = role.get_role_by_name(vo, access_token);
             li.add(role_by_name.get(roleIds.get(i)));
        }
        user.setRoleIds(li);



        //end
        String url=PropertiesUtils.loadProperties("openapi").getProperty("adduser");
        String ip=PropertiesUtils.loadProperties("openapi").getProperty("ip");
        String path="http://"+ip+""+url;
        String post = HttpUtils.doPost2(path,  JSON.toJSONString(user),access_token);
        Object parse = JSON.parse(post);
        return parse;
    }
    //编辑用户
    public Object modifyuser(UserEntity user,String access_token)throws Exception{
        //先判断部门是否存在
        String oldName=user.getEmail();
        String newName=user.getName();

        user.setEmail("");
        Department dept=new Department();
        Map<String, Object> map = dept.searchDepartmentByDepartmentName(user.getDepartmentId(), true);
        if(map.get(user.getDepartmentId())==null){
            return null;
        }
        user.setDepartmentId(map.get(user.getDepartmentId()).toString());
        //查询用户是否存在
        UserSearchEntity use=new UserSearchEntity();
        //use.setFilterType("admin");
        use.setPage(0);
        use.setSize(1000);
        use.setWd(oldName);
        Map<String, Object> searchuser = searchuser(use, access_token);
        if(searchuser.get("name") ==null){
            return 0;
        }
        user.setId(searchuser.get("name").toString());
        List li=new ArrayList();
        //取角色id
        List roleIds = user.getRoleIds();
        Role role=new Role();
        RoleVo vo=new RoleVo();
        for(int i=0;i<roleIds.size();i++){
            vo.setRoleName(roleIds.get(i).toString());
            vo.setRoleType("OTHER");
            Map<String, Object> role_by_name = role.get_role_by_name(vo, access_token);
            li.add(role_by_name.get(roleIds.get(i)));
        }
        user.setRoleIds(new ArrayList());
        //end
        String url=PropertiesUtils.loadProperties("openapi").getProperty("modifyuser");
        String ip=PropertiesUtils.loadProperties("openapi").getProperty("ip");
        String path="http://"+ip+""+url;
        String post = HttpUtils.doPost2(path,  JSON.toJSONString(user),access_token);
        Object parse = JSON.parse(post);
        //角色与用户关联
        //添加角色与用户关联
        RequestRoleAndUser rrau=new RequestRoleAndUser();
        for(int i=0;i<li.size();i++){
            rrau.setRoleId(li.get(i).toString());
            rrau.setOuScope(new ArrayList());
            UserIds userIds=new UserIds();
            userIds.setId(user.getId());
            userIds.setName(user.getName());
            userIds.setUnitType(3);
            List<UserIds> list=new ArrayList<>();
            list.add(userIds);
            rrau.setUserIds(list);
            role.add_role_user(rrau,access_token);
        }

        return parse;
    }
    //删除用户
    public Object deleteuser(UserEntity user,String access_token){
        //通过名称获取id
        //查询用户是否存在
        UserSearchEntity use=new UserSearchEntity();
        //use.setFilterType("admin");
        use.setPage(0);
        use.setSize(1000);
        use.setWd(user.getName());
        Map<String, Object> searchuser = searchuser(use, access_token);
        if(searchuser.get("name") ==null){
            return 0;
        }
        user.setId(searchuser.get("name").toString());

        String url=PropertiesUtils.loadProperties("openapi").getProperty("deleteuser");
        String ip=PropertiesUtils.loadProperties("openapi").getProperty("ip");
        String path="http://"+ip+""+url+"?id="+user.getId();
        String post = HttpUtils.doGet2(path,access_token,null);
        Object parse = JSON.parse(post);
        return parse;
    }
    //查询直接隶属于该组织的用户
    public Object list_user(UserByDepartIdVoEntity vo, String access_token){
      /*  Map<String,String>headers=new HashMap<>();
        headers.put("Accept","application/x-www-form-urlencoded");*/
        String url=PropertiesUtils.loadProperties("openapi").getProperty("list_user");
        String ip=PropertiesUtils.loadProperties("openapi").getProperty("ip");
        String path="http://"+ip+""+url+"?"+vo.toString2();
       String post = HttpUtils.doGet2(path,access_token,null);
       // System.out.println(JSON.toJSONString(vo));
        Object parse = JSON.parse(post);
        return parse;
    }
    //根据用户名或账户名查询用户信息

    public Map<String,Object> searchuser(UserSearchEntity use, String access_token){
        //{"wd":"关键字","page":1,"size":10,"filterType":"admin(admim端人员搜索过滤，主要为过滤应用管理员的查询范围)"}
        String url=PropertiesUtils.loadProperties("openapi").getProperty("searchuser");
        String ip=PropertiesUtils.loadProperties("openapi").getProperty("ip");
        String path="http://"+ip+""+url;
        String post = HttpUtils.doPost2(path,JSON.toJSONString(use),access_token );
        Object parse = JSON.parse(post);
        Map<String,Object> map=new HashMap<>();
         if(((Integer)((JSONObject) parse).get("errcode"))==0){
             JSONArray datas = (JSONArray) ((JSONObject)(((JSONObject)parse).get("data"))).get("content");
             if(datas.size()>0){
                 for(int i=0;i<datas.size();i++){
                     if(use.getWd().equals(((JSONObject)(datas.get(i))).get("name"))){
                         map.put ("name",((JSONObject)(datas.get(i))).get("id"));
                     }
                 }
                 map.put("list",datas);
             }
         }
        return map;
    }

    /**
     * 根据员工名称获取员工所在部门id
     * @param name
     * @param access_token
     * @return
     */
    public String getDeptIdByUser(String name,String access_token){
        UserSearchEntity use=new UserSearchEntity();
        use.setPage(0);
        use.setSize(10);
        use.setWd(name);
        Map<String, Object> searchuser = this.searchuser(use, access_token);
        String deptid = ((JSONArray) searchuser.get("list")).getJSONObject(0).getString("departmentId");
        return deptid;
    }

    public static void main(String[] args) throws Exception{
        /*{"departmentId":"2c2c80867ab40ee9017aca0657a30636","deptIds":[],"username":"用户账号14","name":"用户姓名14","roleIds":[],
            "mobile":"18653178235","officePhone":"","email":"","employeeNo":"2345150","entryDate":"","imgUrl":"","imgUrlId":"","gender":"MALE"}*/
        User user=new User();
        UserEntity u=new UserEntity();
        u.setDepartmentId("2c2c80867ab40ee9017aca0657a30636");
        u.setUsername("test03");
        u.setName("test03");
        u.setEmployeeNo("test03");
        u.setGender("MALE");
        u.setMobile("19612345678");
        u.setDeptIds(new ArrayList());
        u.setEmail("");
        u.setEntryDate("");
        u.setImgUrl("");
        u.setImgUrlId("");
        u.setOfficePhone("");
        u.setRoleIds(new ArrayList());
        u.setUserUnionExtAttrModel(new ArrayList());
        //编辑时
       // u.setId("2c2c80867ab40ee9017ad90af6600776");
        System.out.println(JSON.toJSONString(u));
        String json = "{\"departmentId\":\"2c2c80867ab40ee9017aca0657a30636\",\"deptIds\":[],\"username\":\"tt12221\",\"name\":\"tt12221\",\"roleIds\":[],\"mobile\":\"18653221222\",\"officePhone\":\"\",\"email\":\"\",\"employeeNo\":\"tt12221\",\"entryDate\":\"\",\"imgUrl\":\"\",\"imgUrlId\":\"\",\"gender\":\"MALE\"}";
        System.out.println(json);
        WebApiUtils wau=new WebApiUtils();
        Map<String, String> token = wau.get_token("admin", "123456");
        System.out.println(token.get("access_token"));
        //user.addUser(u,token.get("access_token"));
      // user.modifyuser(u,token.get("access_token"));
       // user.deleteuser(u,token.get("access_token"));
        //  //查询直接隶属于该组织的用户  测试有问题，继续测试
        UserByDepartIdVoEntity vo=new UserByDepartIdVoEntity();
        vo.setDeptId("2c2c80867ab40ee9017aca0657a30636");
        vo.setPage(0);
        vo.setSize(10);
        vo.setFilterType("");
        System.out.println(JSON.toJSONString(vo));
    //  System.out.println(  user.list_user(vo,token.get("access_token")));
        UserSearchEntity use=new UserSearchEntity();
       // use.setFilterType("admin");
        use.setPage(0);
        use.setSize(10);
        use.setWd("x");
        //System.out.println(user.searchuser( use,token.get("access_token")));
        user.getDeptIdByUser("火晓燕",token.get("access_token"));

        /*String url="http://47.100.197.8/api/organization/user/add";
        try {

            UserEntity u=new UserEntity();
            u.setDepartmentId("2c2c80867ab40ee9017aca0657a30636");
            u.setUsername("t100110");
            u.setName("t100110");
            u.setEmployeeNo("t100110");
            u.setGender("MALE");
            WebApiUtils wau=new WebApiUtils();
            Map<String, String> token = wau.get_token("admin", "123456");
            String accesstoken=token.get("access_token");
            URL uRl = new URL(url);
            HttpURLConnection httpConnection =(HttpURLConnection) uRl.openConnection();
            httpConnection.setRequestMethod("POST");
            httpConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpConnection.addRequestProperty("Authorization", "Bearer "+accesstoken);
            //这里就是Bearer+空格+从.net webapi获取的token值
            httpConnection.setDoOutput(true);
            httpConnection.setDoInput(true);
            httpConnection.connect();
            String content=JSON.toJSONString(u);
            OutputStream out = httpConnection.getOutputStream();
            out.write(content.getBytes());
            out.close();

            InputStream is =httpConnection.getInputStream();
            int size = is.available();
            byte[] jsonBytes = new byte[size];
            is.read(jsonBytes);
            String message = new String(jsonBytes,"UTF-8");
            System.out.print(message);
            is.close();
            httpConnection.disconnect();
        } catch (Exception e) {
            e.printStackTrace();
        }*/
    }
}
